const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const upload = require('../utils/upload');
const path = require('path');
const config = require('../config/config.default');
const User = require('../models/user');

// 处理单张图片上传
router.post('/single', auth, upload.single('image'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的图片'
      });
    }

    // 生成图片URL
    const relativePath = path.relative('public/uploads', req.file.path)
      .split(path.sep)
      .join('/');

    const imageUrl = `${config.baseUrl}/uploads/${relativePath}`;

    // 只返回URL
    res.json({
      success: true,
      message: '图片上传成功',
      data: {
        url: imageUrl
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '图片上传失败',
      error: error.message
    });
  }
});

// 处理多张图片上传
router.post('/multiple', auth, upload.array('images', 5), (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的图片'
      });
    }

    // 只返回URL数组
    const urls = req.files.map(file => {
      const relativePath = path.relative('public/uploads', file.path)
        .split(path.sep)
        .join('/');
      return `${config.baseUrl}/uploads/${relativePath}`;
    });

    res.json({
      success: true,
      message: '图片上传成功',
      data: {
        urls: urls
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '图片上传失败',
      error: error.message
    });
  }
});

// 注册用的头像上传接口（不需要token）
router.post('/register/avatar', upload.single('avatar'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的头像'
      });
    }

    // 生成头像URL
    const relativePath = path.relative('public/uploads', req.file.path)
      .split(path.sep)
      .join('/');

    const avatarUrl = `${config.baseUrl}/uploads/${relativePath}`;

    res.json({
      success: true,
      message: '头像上传成功',
      data: {
        url: avatarUrl
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '头像上传失败',
      error: error.message
    });
  }
});

// 更新头像接口（需要token）
router.post('/avatar', auth, upload.single('avatar'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        success: false,
        message: '请选择要上传的头像'
      });
    }

    // 生成头像URL
    const relativePath = path.relative('public/uploads', req.file.path)
      .split(path.sep)
      .join('/');

    const avatarUrl = `${config.baseUrl}/uploads/${relativePath}`;

    // 更新用户头像
    User.findByIdAndUpdate(
      req.user.userId,
      { avatar: avatarUrl },
      { new: true }
    ).then(user => {
      res.json({
        success: true,
        message: '头像上传成功',
        data: {
          url: avatarUrl
        }
      });
    }).catch(error => {
      res.status(500).json({
        success: false,
        message: '更新用户头像失败',
        error: error.message
      });
    });

  } catch (error) {
    res.status(500).json({
      success: false,
      message: '头像上传失败',
      error: error.message
    });
  }
});

// 错误处理中间件
router.use((error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({
        success: false,
        message: '文件大小不能超过5MB'
      });
    }
    if (error.code === 'LIMIT_FILE_COUNT') {
      return res.status(400).json({
        success: false,
        message: '一次最多只能上传5张图片'
      });
    }
  }
  res.status(500).json({
    success: false,
    message: '图片上传失败',
    error: error.message
  });
});

module.exports = router; 